/*
 *
 * -------------------------------------------------------------------------------------------------
 *                            COPYRIGHT(C) BOCO HEALTH 2016
 * -------------------------------------------------------------------------------------------------
 *
 * =================================================================================================
 *  *HISTORY
 *
 *      Tag                Date            Author           Description
 * =================================================================================================
 *      created            2017/1/17      caodailu        create
 * =================================================================================================
 *
 *
 */

package com.boco.base.view.im;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.mobileim.YWConstants;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.channel.cloud.contact.YWProfileInfo;
import com.alibaba.mobileim.channel.util.YWLog;
import com.alibaba.mobileim.contact.IYWContactCacheUpdateListener;
import com.alibaba.mobileim.contact.IYWContactService;
import com.alibaba.mobileim.contact.IYWDBContact;
import com.alibaba.mobileim.conversation.EServiceContact;
import com.alibaba.mobileim.kit.contact.YWContactHeadLoadHelper;
import com.alibaba.mobileim.utility.IMNotificationUtils;
import com.boco.base.App;
import com.boco.base.R;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ContactProfileFragment extends Fragment {


    @BindView(R.id.aliwx_block_bg)
    ImageView mAliwxBlockBg;
    @BindView(R.id.aliwx_people_desc)
    TextView mAliwxPeopleDesc;
    @BindView(R.id.aliwx_people_head)
    ImageView mAliwxPeopleHead;
    @BindView(R.id.aliwx_userid_text)
    TextView mAliwxUseridText;
    @BindView(R.id.aliwx_userid_layout)
    RelativeLayout mAliwxUseridLayout;
    @BindView(R.id.aliwx_remark_name_text)
    TextView mAliwxRemarkNameText;
    @BindView(R.id.aliwx_remark_name_layout)
    RelativeLayout mAliwxRemarkNameLayout;
    @BindView(R.id.aliwx_parallax_view)
    LinearLayout mAliwxParallaxView;
    @BindView(R.id.aliwx_bottom_layout)
    LinearLayout mAliwxBottomLayout;
    @BindView(R.id.head_center_text)
    TextView mHeadCenterText;
    @BindView(R.id.aliwx_bottom_btn)
    Button mAliwxBottomBtn;
    @BindView(R.id.aliwx_btn_send_message)
    Button mAliwxBtnSendMessage;

    private View view;
    private YWIMKit mYWIMKit;
    private YWContactHeadLoadHelper mHelper;
    private YWProfileInfo mYWProfileInfo;
    private String APPKEY;
    private String mUserId;
    private String TAG = ContactProfileFragment.class.getSimpleName();
    private IYWContactCacheUpdateListener mContactCacheUpdateListener;
    private List<IYWDBContact> contactsFromCache;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mYWIMKit = App.getYwimKit();
        mUserId = mYWIMKit.getIMCore().getLoginUserId();
        if (TextUtils.isEmpty(mUserId)) {
            YWLog.i(TAG, "user not login");
        }
        APPKEY = mYWIMKit.getIMCore().getAppKey();


    }

    private void addContactCacheUpdateListener() {
        if (mContactCacheUpdateListener != null && mYWIMKit != null)
            mYWIMKit.getContactService().addContactCacheUpdateListener(mContactCacheUpdateListener);
    }

    private void removeContactCacheUpdateListener() {
        if (mContactCacheUpdateListener != null && mYWIMKit != null)
            mYWIMKit.getContactService().removeContactCacheUpdateListener
                    (mContactCacheUpdateListener);
    }

    private void initContactCacheUpdateListener() {
        mContactCacheUpdateListener = new IYWContactCacheUpdateListener() {

            /**
             * 好友缓存发生变化(联系人备注修改、联系人新增和减少等)，可以刷新使用联系人缓存的UI
             * todo 该回调在UI线程回调 ，请勿做太重的操作
             *
             * @param currentUserid                 当前登录账户
             * @param currentAppkey                 当前Appkey
             */
            @Override
            public void onFriendCacheUpdate(String currentUserid, String currentAppkey) {
                IParent superParent = getSuperParent();
                if (superParent != null) {
                    checkIfHasContact(superParent.getYWProfileInfo());
                    initData();
                }


            }
        };
    }

    private void checkIfHasContact(YWProfileInfo mYWProfileInfo) {
        //修改hasContactAlready和contactsFromCache的Fragment生命周期缓存
        IParent superParent = getSuperParent();
        if (superParent != null) {
            contactsFromCache = getContactService().getContactsFromCache();
            for (IYWDBContact contact : contactsFromCache) {
                if (contact.getUserId().equals(mYWProfileInfo.userId)) {
                    superParent.setHasContactAlready(true);
                    return;
                }

            }
            superParent.setHasContactAlready(false);
        }

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        if (view == null) {
            initContactCacheUpdateListener();
        }
        addContactCacheUpdateListener();

        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
            return view;
        }
        view = inflater.inflate(R.layout.fragment_contact_profile, null);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void initTitle() {

        mHeadCenterText.setVisibility(View.VISIBLE);
        mHeadCenterText.setText("个人资料");

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        removeContactCacheUpdateListener();
    }

    private void init() {
        initTitle();
        initSearchResultView();
        initHelper();
        initData();

    }

    private IParent getSuperParent() {
        IParent superParent = (IParent) getActivity();
        return superParent;
    }

    private IYWContactService getContactService() {
        IYWContactService contactService = mYWIMKit.getContactService();
        return contactService;
    }

    private void initData() {
        IParent superParent = getSuperParent();
        mYWProfileInfo = superParent.getYWProfileInfo();
        hasContactAlready = superParent.isHasContactAlready();
        clearProfileResult();
        showProfileResult(mYWProfileInfo);
    }

    private void initHelper() {
        mHelper = new YWContactHeadLoadHelper(this.getActivity(), null, mYWIMKit.getUserContext());
    }

    public boolean onBackPressed() {
        getSuperParent().finish(false);
        return true;
    }

    //--------------------------[搜索到的联系人的展示]相关实现

    private boolean hasContactAlready;

    private void initSearchResultView() {

        mAliwxParallaxView.setVisibility(View.GONE);
        mAliwxBlockBg.setImageResource(R.drawable.aliwx_head_bg_0);
        mAliwxPeopleDesc.setMaxLines(2); // 必须函数设置，否则无效

    }

    public void clearProfileResult() {
        mAliwxParallaxView.setVisibility(View.GONE);
    }

    public void showProfileResult(final YWProfileInfo lmYWProfileInfo) {


        if (lmYWProfileInfo == null || TextUtils.isEmpty(lmYWProfileInfo.userId)) {
            IMNotificationUtils.getInstance().showToast(ContactProfileFragment.this.getActivity()
                    , "服务开小差，建议您重试搜索");
            return;
        }

        mYWProfileInfo = lmYWProfileInfo;
        setProfileResult(lmYWProfileInfo);
        setBottomView(lmYWProfileInfo);
        mAliwxParallaxView.setVisibility(View.VISIBLE);

    }

    public void setProfileResult(YWProfileInfo profileInfo) {
        if (profileInfo != null) {
            RelativeLayout useridLayout = (RelativeLayout) view.findViewById(R.id
                    .aliwx_userid_layout);
            if (TextUtils.isEmpty(profileInfo.userId)) {
                useridLayout.setVisibility(View.GONE);
            } else {
                useridLayout.setVisibility(View.VISIBLE);
                TextView textView = (TextView) view.findViewById(R.id.aliwx_userid_text);
                textView.setText(new StringBuilder("  ").append(profileInfo.userId));
            }
            RelativeLayout settingRemarkNameLayout = (RelativeLayout) view.findViewById(R.id
                    .aliwx_remark_name_layout);
            if (TextUtils.isEmpty(profileInfo.nick)) {
                settingRemarkNameLayout.setVisibility(View.GONE);
            } else {
                settingRemarkNameLayout.setVisibility(View.VISIBLE);
                TextView textView = (TextView) view.findViewById(R.id.aliwx_remark_name_text);
                textView.setText(new StringBuilder("  ").append(profileInfo.nick));
            }
//			if (TextUtils.isEmpty(profileInfo.icon)) {
//				mHeadView.setImageResource(R.drawable.aliwx_head_default);
//			} else if(!TextUtils.isEmpty(profileInfo.userId)&&!TextUtils.isEmpty(profileInfo
// .icon)) {
            mHelper.setHeadView(mAliwxPeopleHead, profileInfo.userId, APPKEY, true);
//			}
        }
    }

    private void sendMessage(YWProfileInfo mYWProfileInfo) {
        if (mYWProfileInfo.userId.equals(mYWIMKit.getIMCore().getLoginUserId())) {
            IMNotificationUtils.getInstance().showToast(this.getActivity(), "这是您自己，无法发送消息");
            return;
        }
        if (APPKEY.equals(YWConstants.YWSDKAppKey)) {
            //TB或千牛客的服账号
            EServiceContact eServiceContact = new EServiceContact(mYWProfileInfo.userId, 0);//
            Intent intent = mYWIMKit.getChattingActivityIntent(eServiceContact);
            startActivity(intent);
        } else {
            Intent intent = mYWIMKit.getChattingActivityIntent(mYWProfileInfo.userId, APPKEY);
            startActivity(intent);
        }
    }


    private void setBottomView(YWProfileInfo lmYWProfileInfo) {
        /* 对应账号以及好友关系所能够进行的操作*/


        if (mYWProfileInfo.userId.equals(mYWIMKit.getIMCore().getLoginUserId())) {
            mAliwxBottomLayout.setVisibility(View.GONE);
            IMNotificationUtils.getInstance().showToast(this.getActivity(), "这是您自己");
            return;
        } else if (hasContactAlready) {
            mAliwxBottomLayout.setVisibility(View.VISIBLE);
            mAliwxBottomBtn.setVisibility(View.GONE);
            mAliwxBtnSendMessage.setVisibility(View.VISIBLE);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mAliwxBtnSendMessage
                    .getLayoutParams();
            layoutParams.width = getResources().getDimensionPixelSize(
                    R.dimen.aliwx_friend_info_btn_width);
            layoutParams.weight = 0;
            mAliwxBtnSendMessage.setLayoutParams(layoutParams);
//			ToastHelper.showToastMsg(this.getActivity(), "已有该联系人");
        } else {
            mAliwxBottomLayout.setVisibility(View.VISIBLE);
            LinearLayout.LayoutParams bLayoutParams = (LinearLayout.LayoutParams) mAliwxBottomBtn
                    .getLayoutParams();
            bLayoutParams.width = 0;
            bLayoutParams.weight = 1;
            mAliwxBottomBtn.setLayoutParams(bLayoutParams);
            mAliwxBottomBtn.setVisibility(View.VISIBLE);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mAliwxBtnSendMessage
                    .getLayoutParams();
            layoutParams.width = 0;
            layoutParams.weight = 1;
            mAliwxBtnSendMessage.setLayoutParams(layoutParams);
            mAliwxBtnSendMessage.setVisibility(View.VISIBLE);
        }

    }

    @OnClick({R.id.aliwx_bottom_btn, R.id.aliwx_btn_send_message, R.id.head_left_show})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.aliwx_bottom_btn:
                getSuperParent().addFragment(new AddContactFragment(), true);
                break;
            case R.id.aliwx_btn_send_message:
                sendMessage(mYWProfileInfo);
                break;
            case R.id.head_left_show:
                onBackPressed();
                break;
        }
    }
}